<template>
  <div class="content">
    <div class="toolbar" v-if="!files_is_format">
      <el-input placeholder="搜索文件" v-model="file_search_input" class="input-with-select">
        <el-button slot="append" icon="el-icon-search" @click="file_search"></el-button>
      </el-input>
      <el-upload
        class="file_upload"
        action="http://localhost:8080/file/upload"
        v-if="file_allow_write"
        :show-file-list="false"
        :headers="headers"
        :data="{
          'path':file_path
        }"
        :on-success="file_Upload_Success"
      >
        <el-button type="primary">上传文件</el-button>
      </el-upload>
      <el-button @click="files_mkdir" :disabled="!file_allow_write">新建文件夹</el-button>
    </div>
    <div class="file_address_breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item v-for="(item,index) in file_address_breadcrumb" :key="index">
          <el-link :underline="false" @click="file_Address_Breadcrumb_Click(index)">{{item}}</el-link>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <el-table :data="file_list" border style="width: 100%; text-align: center;" height="600">
      <el-table-column prop="name" label="文件名称">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="
                  if (scope.row.name.substr(scope.row.name.length - 1) == '/') {
                    files_Click_Dir(scope.row.name)
                  } else {
                    files_Click_file(scope.row.name)
                  }
                "
          >
            <div>
              <svg-icon
                :name="fileUtils.checkFileType(scope.row.name)"
                style="font-size: 30px; margin-right: 10px;"
              />
              <span
                style="position: absolute; top: 42%;"
              >{{ file_public_dir_handle(scope.row.name) }}</span>
            </div>
          </el-button>

          <el-button-group>
            <el-button type="text" v-if="!files_is_recycle & !files_is_parvate ">
              <svg-icon name="share_1" @click="file_share(scope.row.name)" />
            </el-button>
            <el-button type="text" v-if="!files_is_recycle & !files_is_parvate">
              <svg-icon name="down" @click="file_download(scope.row.name)" />
            </el-button>

            <el-dropdown trigger="click" @command="dropdown_handler" v-if="file_allow_write">
              <span class="el-dropdown-link">
                <el-button type="text" icon="el-icon-more"></el-button>
              </span>
              <el-dropdown-menu slot="dropdown" v-if="!files_is_recycle & !files_is_parvate">
                <el-dropdown-item
                  v-if="files_is_team && $auth('team.manage')"
                  :command="{name:scope.row.name,mode:'set_dir_permission'}"
                >设置文件夹权限</el-dropdown-item>
                <el-dropdown-item :command="{name:scope.row.name,mode:'move'}">移动到</el-dropdown-item>
                <el-dropdown-item
                  v-if="!files_is_team"
                  :command="{name:scope.row.name,mode:'move_private'}"
                >移至隐私空间</el-dropdown-item>
                <el-dropdown-item :command="{name:scope.row.name,mode:'copy'}">复制到</el-dropdown-item>
                <el-dropdown-item :command="{name:scope.row.name,mode:'rename'}">重命名</el-dropdown-item>
                <el-dropdown-item :command="{name:scope.row.name,mode:'del'}">删除</el-dropdown-item>
              </el-dropdown-menu>
              <el-dropdown-menu slot="dropdown" v-if="files_is_recycle">
                <el-dropdown-item :command="{name:scope.row.name,mode:'recovery'}">恢复文件</el-dropdown-item>
                <el-dropdown-item :command="{name:scope.row.name,mode:'del_thorough'}">彻底删除</el-dropdown-item>
              </el-dropdown-menu>
              <el-dropdown-menu slot="dropdown" v-if="files_is_parvate">
                <el-dropdown-item :command="{name:scope.row.name,mode:'move_public'}">移至正常空间</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-button-group>
        </template>
      </el-table-column>
      <el-table-column prop="size" label="文件大小" width="100">
        <template slot-scope="scope">{{scope.row.size}}</template>
      </el-table-column>
      <el-table-column prop="lastModified" label="修改时间" width="200">
        <template slot-scope="scope">{{scope.row.lastModified}}</template>
      </el-table-column>
    </el-table>
    <dir-list v-model="dir_list_data" />
    <div class="share_box">
      <el-dialog
        title="分享文件"
        :visible.sync="shareBox_is_visible"
        :close-on-click-modal="false"
        width="40%"
      >
        <div style="margin-top: 20px;" v-loading="share.loading">
          <el-row :gutter="12">
            <el-col :span="5">
              <span style="line-height: 36px;">分享类型:</span>
            </el-col>
            <el-col :span="12">
              <el-radio-group v-model="share_choice">
                <el-radio-button label="私密">私密</el-radio-button>
                <el-radio-button label="公开">公开</el-radio-button>
              </el-radio-group>
            </el-col>
          </el-row>
          <el-row :gutter="12">
            <el-col :span="5">
              <span style="line-height: 36px;">文件地址:</span>
            </el-col>
            <el-col :span="12">
              <el-input v-model="share.key" placeholder="未生成" style="width: 20vw;"></el-input>
            </el-col>
          </el-row>
          <el-row :gutter="12" v-if="share_choice != '公开'">
            <el-col :span="5">
              <span style="line-height: 36px;">提取密码:</span>
            </el-col>
            <el-col :span="12">
              <el-input v-model="share.pwd" placeholder="未生成" style="width: 10vw;"></el-input>
            </el-col>
          </el-row>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="shareBox_is_visible = false">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getFileList, mkDir, del, rename, copy, move, search, download, format, movePrivate, setDirPermission } from '@/api/requests/file'
import { addShare } from '@/api/requests/share'

import fileUtils from '@/util/file'
import { success, yesOrNo, inputDialog } from '@/util/message'
import store from '@/store/index'
import dir_list from './dir_list'


export default {
  name: "file",
  props: ['format', 'value', 'team_choice_item_allow_write', 'team_role'],
  data () {
    return {
      fileUtils,
      file_path: '/',
      file_list: [],
      file_search_input: '',
      file_address_breadcrumb: ['全部文件'],
      dir_list_data: {
        type: 'move',
        visible: false,
        path: '',
        choice: '',
        isReq: false
      },
      files_is_format: false,
      files_is_recycle: false,
      files_is_parvate: false,
      files_is_team: false,
      shareBox_is_visible: false,
      share_choice: '私密',
      share: {
        key: '',
        pwd: '',
        fileName: '',
        loading: false,
      },
      file_allow_write: true,
      headers: {
        'Authorization': store.state.user.token,
        'team': window.encodeURIComponent(localStorage.getItem('team'))
      },
    }
  },
  created () {
    localStorage.removeItem('recycle')
    localStorage.removeItem('private')
    if (this.value == undefined) {
      localStorage.removeItem('team')
    } else {
      this.files_is_team = true
    }
    if (this.format != undefined) {
      this.files_is_format = true
      this.files_is_recycle = this.format == 'recycle'
      this.files_is_parvate = this.format == 'private'
      if (this.files_is_recycle || this.files_is_parvate) {
        localStorage.setItem(this.format, 0)
        this.files_get_list(this.file_path)
        return
      }

      this.files_get_format_list(this.format)
      return
    }
    if (this.team_choice_item_allow_write != undefined) {
      if (localStorage.getItem('team').indexOf('学院') != -1) {
        this.file_allow_write = this.team_choice_item_allow_write
      }

    }

    this.files_get_list(this.file_path)


  },
  components: {
    "dir-list": dir_list
  },
  watch: {
    file_path (value) {
      if (value.indexOf(':PUBLIC') != -1) {
        this.file_allow_write = true
      } else {
        if (this.team_role == 'student') {
          this.file_allow_write = false
        }
      }
      this.file_Address_Breadcrumb_Change(value)
      if (value == `/搜索:${this.file_search_input}`) {
        this.file_search_request()
        return
      }
      this.files_get_list(value)
    },
    dir_list_data: {
      handler (value) {
        if (!value.isReq) {
          return
        }
        switch (value.type) {
          case 'move':
            this.file_move_request(value.path, value.choice)
            break;
          case 'copy':
            this.file_copy_request(value.path, value.choice)
            break;
          default:
            break;
        }
      },
      deep: true
    },
    value (val) {
      this.file_allow_write = this.team_choice_item_allow_write
      this.files_get_list(this.file_path)

    },
    share_choice (val) {
      this.file_share_request()
    },

  },
  methods: {

    files_get_list (path) {
      getFileList(path).then(res => {
        this.files_refresh_list(res)
      })
    },
    files_get_format_list (format_) {
      format(format_).then(res => {
        this.files_refresh_list(res)
      })
    },
    files_refresh_list (res) {
      this.file_list = []
      let file_list_data = JSON.parse(res.data)
      let file_list_ = []
      file_list_data.forEach(item => {
        item.size = fileUtils.fileSizeToStr(item.size)
        item.lastModified = fileUtils.timestampToTime(item.lastModified)
        //此处为了保证文件夹顺序在文件之前，所以如果不是文件夹都保存在 「file_list_」 之中。之后再 push。
        if (fileUtils.checkFileType(item.name) == '文件夹') {
          this.file_list.push(item)
        } else {
          file_list_.push(item)
        }
      })
      file_list_.forEach(item => {
        this.file_list.push(item)
      })

    },
    files_refresh () {
      this.files_get_list(this.file_path)
    },
    files_mkdir () {
      let that = this
      inputDialog(this, '创建文件夹', '请输入文件夹名称', (value) => {
        mkDir(that.file_path, value).then(res => {
          that.files_refresh_list(res)
          that.$message({
            type: 'success',
            message: '新建成功'
          });
        })
      })
        , null

    },
    files_Click_file (name) {
    },
    files_Click_Dir (name) {
      this.file_path += name
    },
    file_Address_Breadcrumb_Change (path) {
      this.file_address_breadcrumb = ['全部文件']
      path.split('/').forEach(item => {
        if (item != '') {
          this.file_address_breadcrumb.push(item)
        }
      })
    },
    file_Address_Breadcrumb_Click (index) {
      if (index == 0) {
        this.file_path = '/'
        return
      }
      let path = '/'
      let arr = this.file_address_breadcrumb
      for (let i = 1; i <= index; i++) {
        path += arr[i] + '/'
      }
      this.file_path = path
    },
    file_Upload_Success (response) {
      this.$notify({
        title: '成功',
        message: '上传文件成功',
        type: 'success'
      });
      this.files_get_list(this.file_path)
    },
    file_delete (path, name) {

      let p = path + name
      if (this.files_is_team) {
        this.file_delete_request(p, false)
        return
      }
      yesOrNo(this, '是否将文件移至回收站?', () => {
        this.file_delete_request(p, true)

      }, () => {
        this.file_delete_request(p, false)
      })

    },
    file_delete_request (p, isRecycle) {
      let that = this
      del(p, isRecycle).then(res => {
        if (res.code == 200) {
          success(that, '删除成功')
          that.files_refresh()
        }
      })
    },
    file_download (name) {
      let path = this.file_path
      if (this.file_path == `/搜索:${this.file_search_input}`) {
        path = '/'
      }
      download(path + name).then(res => {
        let type = '/'
        if (name.indexOf('.') == -1) {
          name = name.substr(0, name.length - 1) + '.zip'
        }
        fileUtils.download(name, res.data)
      })
    },
    file_rename (path, name) {
      let that = this
      inputDialog(this, '请输入新名称', `重命名文件/文件夹,当前名称: ${name}`, (value) => {
        rename(path, name, value).then(res => {
          that.files_refresh()
          success(that, "重命名成功")
        })
      })
        , null
    },
    file_move (path, name) {
      this.display_Dir_List("move", path + name)
    },
    file_move_request (path, choice) {
      move(path, choice).then(res => {
        if (res.code == 200) {
          success(this, '移动成功')
          this.files_refresh()
        }
      })
      this.dir_list_data.isReq = false

    },
    file_move_private (path) {
      movePrivate(path).then(res => {
        if (res.code == 200) {
          success(this, '移动成功')
          this.files_refresh()
        }
      })
    },
    file_copy (path, name) {
      this.display_Dir_List("copy", path + name)
    },
    file_search () {
      this.file_path = `/搜索:${this.file_search_input}`
    },
    file_search_request () {
      let name = this.file_search_input
      search(name).then(res => {
        if (res.code == 200) {
          this.files_refresh_list(res)
        }
      })
    },
    file_share (name) {
      this.shareBox_is_visible = true
      this.share.fileName = name
      this.file_share_request()
    },
    file_share_request () {
      this.share.loading = true
      let path = this.file_path
      if (this.file_path == `/搜索:${this.file_search_input}`) {
        path = '/'
      }
      path += this.share.fileName
      addShare(path, this.share_choice == '私密').then(res => {
        setTimeout(() => {
          this.share.key = window.location.host + '/#/share/' + res.shareKey
          this.share.pwd = res.sharePwd
          fileUtils.copyToClipboard(this.share.key)
          success(this, '地址已复制到你的剪辑版~')
          this.share.loading = false
        }, 1100)

      })
    },
    file_copy_request (path, choice) {
      copy(path, choice).then(res => {
        if (res.code == 200) {
          success(this, '复制成功')
          this.files_refresh()
        }
      })
      this.dir_list_data.isReq = false
    },
    file_team_set_DirPermission (path) {
      setDirPermission(path).then(res => {
        if (res.code == 200) {
          success(this, '设置成功')
          this.files_refresh()

        }
      })
    },
    dir_list_data_reload () {
      this.dir_list_data.choice = ""
      this.dir_list_data.path = this.file_path

    },
    dropdown_handler ({ name, mode }) {
      let path = this.file_path
      if (this.file_path == `/搜索:${this.file_search_input}`) {
        path = '/'
      }
      switch (mode) {
        case 'del':
          this.file_delete(path, name)
          break
        case 'del_thorough':
          this.file_delete_request(path + name, false)
          break
        case 'rename':
          this.file_rename(path, name)
          break
        case 'copy':
          this.file_copy(path, name)
          break
        case 'move':
          this.file_move(path, name)
          break
        case 'move_private':
          this.file_move_private(path + name)
          break
        case 'move_public':
          this.file_move_request(path + name, '/')
          break
        case 'recovery':
          this.file_move_request(path + name, '/')
          break
        case 'set_dir_permission':
          this.file_team_set_DirPermission(path + name)
          break
        case 'download':
          break
        default:
          break;
      }
    },
    display_Dir_List (type, path) {
      this.dir_list_data.type = type
      this.dir_list_data.visible = true
      this.dir_list_data.path = path
    },
    file_public_dir_handle (val) {
      return val.replace(':PUBLIC', '')
    },





  },
}
</script>

<style lang="scss" scoped>
.content {
    padding: 20px 50px;
}
.el-button-group {
    position: absolute;
    right: 22px;
    top: 21%;
    .el-button--text {
        color: #000;
        font-size: 20px;
        margin-right: 5px;
    }
    .el-button--text:hover {
        color: #00a4f1;
    }
}
.el-dropdown-menu {
    margin-top: -10px;
}
.share_box {
    .el-row {
        margin-bottom: 10px;
    }
}
</style>

<style lang="scss">
.toolbar,
.file_address_breadcrumb {
    margin-bottom: 20px;
}
.toolbar {
    display: flex;
    .input-with-select,
    .file_upload {
        margin-right: 20px;
    }
    .input-with-select {
        width: 200px;
    }
}
.notice_alert {
    width: 70vw;
    min-height: 50vh;
}
</style>